<?php

namespace App\Http\Requests;

use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;

class BaseRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    protected $strings_val = [
        'required'=> '为必填项',
        'min'=> '最小为:min',
        'max'=> '最大为:max',
        'between'=> '长度在:min和:max之间',
        'integer'=> '必须为整数',
        'exists'=> '不存在',
        'unique'=> '已存在',
    ];

    //返回给前台的错误信息
    public function messages(){
        $rules = $this->rules();
        $array=[];
        if(count($rules)>0){
            $k_array = $this->strings_key;
            $v_array = $this->strings_val;
            foreach ($rules as $key => $value) {
                $new_arr = explode('|', $value);//分割成数组
                foreach ($new_arr as $k => $v) {
                    $head = strstr($v,':',true);//截取:之前的字符串
                    if ($head) {$v = $head;}
                    $array[$key.'.'.$v] = $k_array[$key].$v_array[$v];
                }
            }
        }
        return $array;
    }

    public function failedValidation(Validator $validator)
    {
        throw (new HttpResponseException(response()->json([
            'status' => false,
            'code' => 500,
            'message' => '请求错误 验证不通过',
            'data' => $validator->errors(),
        ], 200)));
    }
}
